<template>
  <el-card>
    <div slot="header">
      <div class="header-content">
        <span>报销清单</span>
        <el-button
          v-if="(controlData.workflow || {}).taskName === '发起申请'"
          type="primary"
          size="small"
          @click="onAdd"
        >添加</el-button>
      </div>
    </div>
    <div>
      <vxe-table
        ref="reimbursementTableRef"
        :data="reimbursementDetails"
        :highlight-current-row="true"
        :highlight-hover-row="true"
        :highlight-current-column="true"
        :highlight-hover-column="true"
        :auto-resize="true"
        align="center"
      >
        <vxe-column type="seq" width="60" title="序号" show-overflow />
        <vxe-column field="affiliationName" title="项目/合同" show-overflow />
        <vxe-column field="purpose" title="用途" show-overflow />
        <vxe-column
          field="purposeType"
          title="用途类型"
          show-overflow
          :formatter="purposeTypeFormatter"
        />
        <vxe-column field="months" title="报销月份" show-overflow />
        <vxe-column field="amount" title="金额(元)" :formatter="formatAmount" show-overflow />
        <vxe-column
          field="accountingType"
          title="核算类型"
          show-overflow
          :formatter="accountingTypeFormatter"
        />
        <vxe-column field="accountingDepartmentName" title="核算部门" show-overflow />
        <vxe-column field="remark" title="备注" show-overflow :edit-render="{ name: 'input' }" />
        <vxe-column
          v-if="(controlData.workflow || {}).taskName === '发起申请'"
          title="操作"
          width="150"
          show-overflow
        >
          <template #default="{ row, rowIndex }">
            <el-button icon="fa fa-edit" type="text" size="mini" @click="onEdit(row, rowIndex)">编辑</el-button>
            <el-button type="text" icon="fa fa-trash-o" size="mini" @click="onRemove(rowIndex)">删除</el-button>
          </template>
        </vxe-column>
      </vxe-table>
    </div>

    <vxe-modal
      v-model="modalVisible"
      :resize="true"
      width="500"
      height="450"
      title="报销清单"
      show-zoom
      destroy-on-close
      :show-footer="true"
      @close="onModalClose"
      :loading="modalLoading"
    >
      <el-form
        ref="detailFormRef"
        label-position="left"
        :model="detailModel"
        :rules="detailRules"
        :label-width="'80px'"
      >
        <el-form-item label="项目/合同" prop="reimbursementAffiliation">
          <el-select
            v-model="detailModel.reimbursementAffiliation"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="projectRemoteMethod"
            clearable
            @change="onProjectChange($event, detailModel)"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.projectId"
              :label="'[' + item.projectCode + ']' + item.projectName"
              :value="item.projectId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用途" prop="purpose">
          <el-input v-model="detailModel.purpose" placeholder="请输入用途" />
        </el-form-item>
        <el-form-item label="用途类型" prop="purposeType">
          <el-select
            v-model="detailModel.purposeType"
            placeholder="请选择用途类型"
            clearable
            filterable
            @change="onPurposeTypeChange($event)"
          >
            <el-option
              v-for="item in controlData.purposeTypeOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <p v-if="isRenderMonths" style="color: red">注：此报销月份对应每月实际报销的月份,可多选。</p>
        <el-form-item v-if="isRenderMonths" label="报销月份" prop="months">
          <multiple-month v-model="detailModel.months" placeholder="请选择报销月份"></multiple-month>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number
            v-model="detailModel.amount"
            :controls="false"
            :precision="2"
            placeholder="请输入金额"
          />
        </el-form-item>
        <el-form-item label="核算类型" prop="accountingType">
          <el-select
            v-model="detailModel.accountingType"
            placeholder="请选择核算类型"
            clearable
            filterable
          >
            <el-option
              v-for="item in controlData.accountingTypeOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="核算部门" prop="accountingDepartmentId">
          <el-select
            v-model="detailModel.accountingDepartmentId"
            placeholder="请选择核算部门"
            clearable
            filterable
            @change="onDeptChange($event)"
          >
            <el-option
              v-for="item in controlData.depOptions"
              :key="item.id"
              :label="item.text"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="detailModel.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="onModelConfirm">确定</el-button>
        <el-button type="info" @click="onModelCancel">取消</el-button>
      </template>
    </vxe-modal>
  </el-card>
</template>

<script>
import request from "@/utils/request";
import MultipleMonth from "./multiple-month/index";
// 数据字典：用途类型-其它
const PURPOSE_TYPE_OTHER_DICT_CODE = "Other";

export default {
  props: {
    reimbursementDetails: {
      type: Array,
      default: () => [],
    },
    controlData: {
      type: Object,
    },
    pageAction: {
      type: String,
    },
    baseInfoModel: {
      type: Object,
    },
  },
  data() {
    return {
      modalLoading: false,
      modalVisible: false,
      isEdit: false,
      editRowIndex: 0,
      detailModel: {
        reimbursementAffiliation: undefined,
        affiliationName: undefined,
        purpose: undefined,
        purposeType: undefined,
        months: undefined,
        amount: undefined,
        accountingType: undefined,
        accountingDepartmentId: undefined,
        accountingDepartmentName: undefined,
        remark: undefined,
      },
      detailRules: {
        purpose: [
          {
            required: true,
            message: "用途不能为空",
            trigger: "blur",
          },
        ],
        purposeType: [
          {
            required: true,
            message: "请选择用途类型",
            trigger: "change",
          },
        ],
        months: [
          {
            required: true,
            message: "请选择报销月份",
            trigger: "change",
          },
        ],
        amount: [
          {
            required: true,
            message: "金额不能为空",
            trigger: "blur",
          },
        ],
        accountingType: [
          {
            required: true,
            message: "核算类型不能为空",
            trigger: "change",
          },
        ],
        accountingDepartmentId: [
          {
            required: true,
            message: "核算部门不能为空",
            trigger: "change",
          },
        ],
      },
      projectOptions: [],
      isRenderMonths: false,
      PURPOSE_TYPE_OTHER_DICT_CODE,
    };
  },
  components: {
    MultipleMonth,
  },
  methods: {
    onAdd() {
      this.loadMyProjects().then((res) => {
        const projectOptions = res.data;
        if (Array.isArray(projectOptions)) {
          this.projectOptions = projectOptions;
        }
        this.detailModel = {
          reimbursementAffiliation: undefined,
          affiliationName: undefined,
          purpose: undefined,
          purposeType: undefined,
          months: undefined,
          amount: undefined,
          accountingType: undefined,
          accountingDepartmentId: this.baseInfoModel.departmentId,
          accountingDepartmentName: this.baseInfoModel.departmentName,
          remark: undefined,
        };
        this.setIsRenderMonths();
        this.isEdit = false;
        this.modalVisible = true;
      });
    },
    onEdit(row, rowIndex) {
      this.loadMyProjects().then((res) => {
        const projectOptions = res.data;
        if (Array.isArray(projectOptions)) {
          this.projectOptions = projectOptions;
        }
        this.detailModel = Object.assign({}, row);
        this.monthsToArray();
        this.setIsRenderMonths();
        this.isEdit = true;
        this.editRowIndex = rowIndex;
        this.modalVisible = true;
      });
    },
    setIsRenderMonths() {
      const purposeType = this.detailModel.purposeType;
      if (purposeType && purposeType !== PURPOSE_TYPE_OTHER_DICT_CODE) {
        this.isRenderMonths = true;
      } else {
        this.isRenderMonths = false;
      }
    },
    onRemove(rowIndex) {
      const reimbursementDetails = this.reimbursementDetails;
      if (
        Array.isArray(reimbursementDetails) &&
        reimbursementDetails.length > rowIndex
      ) {
        reimbursementDetails.splice(rowIndex, 1);
        this.$emit("onChange", reimbursementDetails);
      }
    },
    projectRemoteMethod(params) {
      this.loadMyProjects(params).then((res) => {
        this.projectOptions = res.data;
      });
    },
    loadMyProjects(params) {
      return new Promise((rs, rj) => {
        this.modalLoading = true;
        request({
          url: "/eip/project2/getProjects",
          method: "get",
          params: { term: params },
        })
          .then((res) => {
            rs(res);
          })
          .catch((eerror) => {
            this.msgError(error || "数据请求失败");
            rj(error);
          })
          .finally(() => {
            this.modalLoading = false;
          });
      });
    },
    onModelConfirm() {
      this.$refs["detailFormRef"].validate((valid) => {
        if (valid) {
          let reimbursementDetails = _.cloneDeep(this.reimbursementDetails);
          reimbursementDetails =
            Array.isArray(reimbursementDetails) &&
            reimbursementDetails.length > 0
              ? reimbursementDetails
              : [];

          this.monthsToString();
          if (this.isEdit) {
            reimbursementDetails[this.editRowIndex] = Object.assign(
              {},
              this.detailModel
            );
          } else {
            reimbursementDetails.unshift(Object.assign({}, this.detailModel));
          }
          this.$emit("onChange", _.cloneDeep(reimbursementDetails));
          this.onModelCancel();
        }
      });
    },
    monthsToString() {
      const months = this.detailModel.months;
      if (Array.isArray(months)) {
        this.detailModel.months = months.toString();
      }
    },
    monthsToArray() {
      const months = this.detailModel.months;
      if (months) {
        this.detailModel.months = months.split(",");
      }
    },
    onModelCancel() {
      this.modalVisible = false;
      this.resetDetailForm();
    },
    onModalClose() {
      this.resetDetailForm();
    },
    onPurposeTypeChange(purposeType) {
      if (purposeType && purposeType !== PURPOSE_TYPE_OTHER_DICT_CODE) {
        this.isRenderMonths = true;
      } else {
        this.isRenderMonths = false;
        this.detailModel.months = undefined;
      }
    },
    onDeptChange(departmentId) {
      let departmentName;
      if (typeof departmentId === "string" && departmentId.trim().length > 0) {
        const depOptions = this.controlData.depOptions;
        if (Array.isArray(depOptions)) {
          const findOption = depOptions.find(
            (item) => item.id === departmentId
          );
          departmentName = findOption ? findOption.text : undefined;
        }
      }
      this.detailModel.accountingDepartmentName = departmentName;
    },
    resetDetailForm() {
      if (this.$refs["detailFormRef"]) {
        this.$refs["detailFormRef"].clearValidate();
      }
    },
    formatAmount({ cellValue }) {
      return parseFloat(cellValue).toFixed(2);
    },
    accountingTypeFormatter({ cellValue, row, column }) {
      if (typeof cellValue === "string" && cellValue.trim().length > 0) {
        const accountingTypeOptions = this.controlData.accountingTypeOptions;
        if (Array.isArray(accountingTypeOptions)) {
          const findOption = accountingTypeOptions.find(
            (item) => item.code === cellValue
          );
          return findOption ? findOption.name : cellValue;
        }
      }
      return cellValue;
    },
    purposeTypeFormatter({ cellValue, row, column }) {
      if (typeof cellValue === "string" && cellValue.trim().length > 0) {
        const purposeTypeOptions = this.controlData.purposeTypeOptions;
        if (Array.isArray(purposeTypeOptions)) {
          const findOption = purposeTypeOptions.find(
            (item) => item.code === cellValue
          );
          return findOption ? findOption.name : cellValue;
        }
      }
      return cellValue;
    },
    onProjectChange(val, detailModel) {
      const find = this.projectOptions.find((item) => item.projectId === val);
      if (find) {
        detailModel.affiliationName = find.projectName;
      }
    },
  },
};
</script>
